<template>
  <div>
    <a-row :gutter="8">
      <a-card>
        <a-col :span="24">
          <a-row>
            <a-col :span="24">
              <a-form layout="horizontal">
                <a-form-item label="评估时间" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                  <range-date @change="handleDateChange" style="width: 50%" ref="createTime"></range-date>
                  <a-button style="margin-left: 8px" type="primary" @click="search">查询</a-button>
                  <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                </a-form-item>
              </a-form>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-card>
                <apexchart
                  type="line"
                  height="350"
                  width="100%"
                  :options="chartOptions"
                  :series="series"
                />
              </a-card>
            </a-col>
          </a-row>
        </a-col>
      </a-card>
    </a-row>
    <a-row :gutter="8">
      <a-col :span="12">
        <a-card>
          <high-charts ref="highCharts" :options="options" :styles="styles"></high-charts>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card title="现场情况">
          <!-- <div style="width: 550px;height: 348px;background:#D1EEEE"></div> -->
          <div
            class="demo-infinite-container"
            v-infinite-scroll="handleInfiniteOnLoad"
            :infinite-scroll-disabled="busy"
            :infinite-scroll-distance="10"
          >
            <a-list :dataSource="recordData">
              <a-list-item slot="renderItem" slot-scope="item, index">
                <a-list-item-meta
                  :description="item.recordClass == 1 ? '符合项': item.recordClass == 2 ? '一般隐患' : '重大隐患'"
                >
                  <a slot="title" :href="item.href" @click="view(index,item)">{{item.recordTerms}}</a>
                  <a-avatar slot="avatar" src="../static/avatar/warning.jpg" />
                </a-list-item-meta>
              </a-list-item>
              <div v-if="loading && !busy" class="demo-loading-container">
                <a-spin />
              </div>
            </a-list>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <!-- 用户信息查看 -->
    <warning-info
      :warningInfoData="warningInfo.data"
      :warningInfoVisiable="warningInfo.visiable"
      @close="handleWarningInfoClose"
    ></warning-info>
  </div>
</template>
<script>
import RangeDate from "@/components/datetime/RangeDate";
import HighCharts from "@/components/highCharts/HighCharts";
import { mapState } from "vuex";
import moment from "moment";
import reqwest from "reqwest";
import infiniteScroll from "vue-infinite-scroll";
import WarningInfo from "./WarningInfo";

moment.locale("zh-cn");
const fakeDataUrl =
  "https://randomuser.me/api/?results=5&inc=name,gender,email,nat&noinfo";
export default {
  name: "AssessInfo",
  directives: { infiniteScroll },
  components: { RangeDate, HighCharts, WarningInfo },
  data() {
    let self = this;
    return {
      warningInfo: {
        visiable: false,
        data: {}
      },
      queryParams: {},
      series: [
        {
          name: "分数",
          data: []
        }
      ],
      chartOptions: {
        chart: {
          height: 350,
          zoom: {
            enabled: false
          },
          events: {
            dataPointSelection: function(event, chartContext, config) {
              self.setPiData(config.dataPointIndex);
            }
          }
        },
        tooltip: {
          intersect: true,
          shared: false
        },
        markers: {},
        dataLabels: {
          enabled: false
        },
        stroke: {
          curve: "straight"
        },
        title: {
          text: "安全生产监督检查信息趋势图",
          align: "center"
        },
        grid: {
          row: {
            colors: [
              "#99ccff",
              "#99ccff",
              "#ffff99",
              "#ffff99",
              "#cc0000",
              "#cc0000",
              "#cc0000",
              "#cc0000",
              "#cc0000",
              "#cc0000"
            ], // takes an array which will be repeated on columns
            opacity: 0.3
          }
        },
        xaxis: {
          categories: []
        },
        yaxis: {
          categories: [
            "0",
            "10",
            "20",
            "30",
            "40",
            "50",
            "60",
            "70",
            "80",
            "90",
            "100"
          ],
          min: 0,
          max: 100,
          tickAmount: 10
        }
      },
      options: {
        chart: {
          type: "pie",
          options3d: {
            enabled: true,
            alpha: 45,
            beta: 0
          }
        },
        title: {
          text: "安全生产监督检查隐患分类占比"
        },
        tooltip: {
          pointFormat: "{series.name}: <b>{point.percentage:.1f}%</b>"
        },
        plotOptions: {
          pie: {
            allowPointSelect: true,
            cursor: "pointer",
            depth: 35,
            dataLabels: {
              enabled: true,
              format: "{point.name}"
            }
          }
        },
        series: [
          {
            type: "pie",
            name: "隐患分类占比",
            data: [
              // ["Firefox", 45.0],
              // ["IE", 26.8],
              // {
              //   name: "Chrome",
              //   y: 12.8,
              //   sliced: true,
              //   selected: true
              // },
              // ["Safari", 8.5],
              // ["Opera", 6.2],
              // ["Others", 0.7]
            ],
            showInLegend: true
          }
        ]
      },
      styles: {
        width: 550,
        height: 400
      },
      records: [],
      loading: false,
      busy: false,
      time: [],
      reportData: [],
      recordSum: 0,
      recordData: []
    };
  },
  beforeMount() {
    let end = new Date();
    let start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
    start = this.$dateUtil.dateFtt(this.$dateUtil.dateStr(start), "yyyy-MM-dd");
    end = this.$dateUtil.dateFtt(this.$dateUtil.dateStr(end), "yyyy-MM-dd");
    this.queryParams.createTimeFrom = start;
    this.queryParams.createTimeTo = end;
    let startStr = "moment(" + start + ",'YYYY-MM-DD')";
    let endStr = "moment(" + end + ",'YYYY-MM-DD')";
    this.time.push(startStr);
    this.time.push(endStr);
  },
  methods: {
    moment,
    handleWarningInfoClose() {
      this.warningInfo.visiable = false;
    },
    view(index, item) {
      this.warningInfo.visiable = true;
      this.warningInfo.data = item;
    },
    handleInfiniteOnLoad() {
      const data = this.recordData;
      this.loading = true;
      if (data.length == this.recordData.length) {
        this.$message.warning("到尽头了");
        this.busy = true;
        this.loading = false;
        return;
      }
    },
    handleDateChange(value) {
      if (value) {
        this.queryParams.createTimeFrom = value[0];
        this.queryParams.createTimeTo = value[1];
      }
    },
    search() {
      let that = this;
      let company = this.$db.get("COMPANY");
      let user = this.$db.get("USER");
      this.queryParams.companyId = company.value
      this.queryParams.reportSelf = '0';
      this.$get("report", {
        ...this.queryParams
      }).then(r => {
        that.reportData = r.data.rows;
        if (r.data.total > 0) {
          that.setPiData(0);
        }
        that.series[0].data = []
        that.chartOptions.xaxis.categories = []
        that.reportData.forEach(report => {
          that.series[0].data.push(report.reportScore);
          that.chartOptions.xaxis.categories.push(report.createTime);
        });
      });
    },
    reset() {
      // 重置查询参数
      this.queryParams = {};
      // 清空时间选择
      this.$refs.createTime.reset();
      this.fetch();
    },
    setPiData(index) {
      let that = this;
      this.options.series[0].data = [];
      this.$get("record/getRecords/" + this.reportData[index].reportId).then(
        r => {
          this.recordData = r.data.rows;
          let oneLevel = 0;
          let twoLevel = 0;
          let threeLevel = 0;
          let that = this;
          this.recordData.forEach(record => {
            if (record.recordClass == 2) {
              twoLevel++;
            }
            if (record.recordClass == 3) {
              threeLevel++;
            }
          });
          let arr1 = new Array();
          arr1[0] = "符合项";
          arr1[1] =
            (1 -
              (twoLevel / this.recordSum).toFixed(4) -
              (threeLevel / this.recordSum).toFixed(4)) *
            100;
          this.options.series[0].data.push(arr1);
          let arr2 = new Array();
          arr2[0] = "一般隐患";
          arr2[1] = (twoLevel / this.recordSum).toFixed(4) * 100;
          this.options.series[0].data.push(arr2);
          let arr3 = new Array();
          arr3[0] = "重大隐患";
          arr3[1] = (threeLevel / this.recordSum).toFixed(4) * 100;
          this.options.series[0].data.push(arr3);
          that.$refs.highCharts.initChart();
        }
      );
    }
  },
  mounted() {
    let that = this;
    let params = {};
    let user = this.$db.get("USER");
    let company = this.$db.get("COMPANY");
    params.companyId = company.value;
    params.officeId = user.officeId==undefined ? null:user.officeId;
    params.reportSelf = '0';
    this.$get("report", {
      ...params
    }).then(r => {
      that.reportData = r.data.rows;
      if (r.data.total > 0) {
        that.setPiData(0);
      }
      that.reportData.forEach(report => {
        that.series[0].data.push(report.reportScore);
        that.chartOptions.xaxis.categories.push(report.createTime);
      });
    });
    this.$get("company/getRecordSum/" + company.value).then(r => {
      that.recordSum = r.data.recordNum;
    });
  }
};
</script>
<style lang="less">
.demo-infinite-container {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: auto;
  padding: 8px 24px;
  height: 348px;
  width: 550px;
}
.demo-loading-container {
  position: absolute;
  bottom: 40px;
  width: 100%;
  text-align: center;
}
</style>
